#include <boost/typeof/typeof.hpp>

#include "uid_comet_conn_map.h"
#include "base/logging.h"
#include "im/adapters/connection_manager_adapter.h"

namespace imserver {

void UidCometConnMap::add(int64_t uid, CometConnectionPtr conn) {
  LOG_INFO("UidConnMap::add --> uid:" << uid);
  int index = (uid/10)%BUCKET_COUNT;
  {
    boost::mutex::scoped_lock lock(mutexies[index]);
    uid_conn_maps_[index][uid] = conn;
  }
  ConnectionManagerAdapter::instance().SetValidCometServiceForUid(uid, g_shard_path);
}

void UidCometConnMap::remove(int64_t uid) {
  LOG_INFO("UidConnMap::remove --> uid:" << uid);
  int index = (uid/10)%BUCKET_COUNT;
  {
    boost::mutex::scoped_lock lock(mutexies[index]);
    BOOST_AUTO(it, uid_conn_maps_[index].find(uid));
    if (it != uid_conn_maps_[index].end()) {
      uid_conn_maps_[index].erase(it);
    }
  }
  std::vector<int64_t> uids;
  uids.push_back(uid);
  ConnectionManagerAdapter::instance().RemoveCometServiceKeyByUids(uids);
}

bool UidCometConnMap::get(int64_t uid, CometConnectionPtr& conn) {
  bool res = false;
  int index = (uid/10)%BUCKET_COUNT;
  boost::mutex::scoped_lock lock(mutexies[index]);
  BOOST_AUTO(it, uid_conn_maps_[index].find(uid));
  if (it != uid_conn_maps_[index].end()) {
    LOG_DEBUG("UidConnMap::get --> get conn. uid:" << uid);
    conn = it->second;
    res = true;
  } else {
    LOG_DEBUG("UidConnMap::get --> conn not found. uid:" << uid);
    res = false;
  }
  return res;
}

}

